package com.dayuan.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.dayuan.bean.BackUser;
import com.dayuan.bean.Goods;
import com.dayuan.bean.MerchantInfo;
import com.dayuan.exception.DeleteException;
import com.dayuan.exception.InsertException;
import com.dayuan.exception.UpdateException;
import com.dayuan.service.AdminUserService;
import com.dayuan.service.GoodsTypeService;
import com.dayuan.service.MerchantInfoService;
import com.dayuan.service.SellerGoodsService;
import com.dayuan.utils.Page;
import com.dayuan.utils.SecurityUtil;
import com.dayuan.vo.GoodsTypeVo;
import com.dayuan.vo.GoodsVo;

/**
 * 商家管理商品
 */
@Controller
@RequestMapping("/seller")
public class SellerGoodsController {

	@Resource
	private SellerGoodsService sellerGoodsService;
	@Resource
	private AdminUserService adminUserService;
	@Resource
	private MerchantInfoService merchantInfoService;
	@Resource
	private GoodsTypeService goodsTypeService;

	@RequestMapping(value = "/toStart.shtml", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toStart() {
		ModelAndView modelAndView = new ModelAndView("sellerGoodsManage");
		return modelAndView;
	}

	@RequestMapping(value = "/toAddGoods.shtml", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddGoods(ModelMap modelMap) {
		// 动态展示三级类目
		List<GoodsTypeVo> typeVos = goodsTypeService.initGoodsTypes(0);
		modelMap.addAttribute("GoodsTypeVo", typeVos);
		ModelAndView modelAndView = new ModelAndView("sellerAddGoods", modelMap);
		return modelAndView;
	}

	@RequestMapping(value = "/selectgoods.shtml", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView sellerSelectGoods(HttpSession session, Goods goods, ModelMap modelMap, Integer pageIndex) {

		ModelAndView modelAndView = null;
		BackUser backUser = SecurityUtil.getBackUser();
		if (backUser == null) {
			modelAndView = new ModelAndView("redirect:/login/hello.shtml");
			return modelAndView;
		}
		backUser = adminUserService.selectAdminUser(backUser);
		MerchantInfo merchantInfo = merchantInfoService.sellerMerchantInfo(backUser.getId());
		if (merchantInfo == null) {
			modelAndView = new ModelAndView("redirect:/login/hello.shtml");
			return modelAndView;
		}

		if (pageIndex == null) {
			pageIndex = 1;
		}
		int total = sellerGoodsService.selcetTotal(goods);
		Page page = new Page(pageIndex, total);
		List<Goods> goodList = sellerGoodsService.sellerSelectGoods(goods, page.getStartIndex(), page.getPageNum());
		List<GoodsVo> goodsVoList = new ArrayList<>();
		for (Goods goodsResult : goodList) {
			GoodsVo goodsVo = new GoodsVo(goodsResult.getId(), goodsResult.getGoodsName(), goodsResult.getGoodsType(),
					goodsResult.getDiscountPrice(), goodsResult.getOrgPrice(), goodsResult.getMerchantId(),
					goodsResult.getPicUrl());
			goodsVoList.add(goodsVo);
		}
		modelMap.addAttribute("goodsVoList", goodsVoList);
		modelMap.addAttribute("page", page);
		modelAndView = new ModelAndView("sellerGoodsManage", modelMap);
		return modelAndView;
	}

	// 添加删除商品功能
	@RequestMapping(value = "/deletegoodss.shtml", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView deletegoodss(HttpServletRequest request, Long id, Integer merchantId) {
		ModelAndView mv = null;
		try {
			int i = sellerGoodsService.deletegoodById(id, merchantId);
			if (i <= 0) {
				throw new DeleteException("删除失败");
			}
			mv = new ModelAndView("redirect:/seller/selectgoods.shtml");
			return mv;
		} catch (DeleteException e) {
			System.out.println(e.toString());
			mv = new ModelAndView("redirect:/seller/selectgoods.shtml");
			mv.addObject("deleteresult", "删除失败，请重试");
			return mv;
		} catch (Exception e) {
			System.out.println(e.toString());
			mv = new ModelAndView("redirect:/seller/selectgoods.shtml");
			mv.addObject("deleteresult", "网络错误");
			return mv;
		}

	}

	// 更新商品
	@RequestMapping(value = "/updategoods.shtml", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView updateGoods(HttpServletRequest request, Goods goods) {
		ModelAndView mv = null;
		try {
			int updateresult = sellerGoodsService.updateGoods(goods);
			if (updateresult <= 0) {
				throw new UpdateException("更新失败");
			}
			mv = new ModelAndView("redirect:/seller/selectgoods.shtml");
			return mv;
		} catch (UpdateException e) {
			System.out.println(e.toString());
			mv = new ModelAndView("redirect:/seller/selectgoods.shtml");
			mv.addObject("updateresult", "更新失败,请重试");
			return mv;

		} catch (Exception e) {
			System.out.println(e.toString());
			mv = new ModelAndView("redirect:/seller/selectgoods.shtml");
			mv.addObject("updateresult", "网络错误");
			return mv;
		}
	}

	// 商家上架商品
	@RequestMapping(value = "/addgoods.shtml", method = { RequestMethod.GET, RequestMethod.POST })
	public String addGoods(@RequestParam(value = "tyty") MultipartFile tyty, HttpServletRequest request,
			ModelMap model, Goods goods) {
		try {
			//插入商品数据（不包含图片）
			BackUser backUser = SecurityUtil.getBackUser();
			if (backUser == null) {
				return "redirect:/login/hello.shtml";
			}
			backUser = adminUserService.selectAdminUser(backUser);
			MerchantInfo merchantInfo = merchantInfoService.sellerMerchantInfo(backUser.getId());
			if (merchantInfo == null) {
				return "redirect:/login/hello.shtml";
			}
			goods.setMerchantId(merchantInfo.getId());
			int insertresult = sellerGoodsService.insertGoodsSelective(goods);
			if (insertresult <= 0) {
				throw new InsertException("增加商品失败");
			}
			//插入成功下载图片生成url
			String path = request.getSession().getServletContext().getRealPath("images");
			System.out.println(path);
			String fileName = tyty.getOriginalFilename();
			// String fileName = new Date().getTime()+".jpg";
			File targetFile = new File(path, fileName);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			// 保存
			try {
				tyty.transferTo(targetFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
			model.addAttribute("fileUrl", request.getContextPath() + "/images/" + fileName);
			// insert数据
			goods.setPicUrl("images/" + fileName);
			
			return "redirect:/seller/selectgoods.shtml";
		} catch (InsertException e) {
			e.printStackTrace();
			model.addAttribute("addgoodsresult", "请输入正确信息");
			return "sellerAddGoods";
		}
	}
}
